import config from './config.js'
import {languages} from "@/locale";
import i18n from "../api/lang";

export function setToken(token) {
    return uni.setStorageSync('token', token);
}

export function removeToken() {
    return uni.removeStorageSync('token');
}

export function getToken() {
    return uni.getStorageSync('token')
}

export function userIsLogin() {
    return !!uni.getStorageSync('token')
}

export function setCache(k, v) {
    return uni.setStorageSync(k, v)
}

export function getCache(k) {
    return uni.getStorageSync(k)
}

export function getLang() {
    let lang = getCache('lang');
    if (!lang) {
        lang = uni.getLocale();
    }
    let languageText = ''
    for (const item of languages) {
        if (item.value === lang) {
            languageText = item.value
        }
    }
    if (!languageText) {
        lang = 'en'
    }
    i18n.locale = lang;
    uni.setLocale(lang)
    setCache('lang', lang)
    return lang
}

export function delCache(k) {
    return uni.removeStorageSync(k)
}

export function getApi(path) {
    return config.api_url + path
}

export function genUrl(url, query) {
    if (!Object.keys(query).length) {
        return url;
    }
    if (url.indexOf('?') === -1) {
        url += '?'
    } else {
        url += '&'
    }
    for (var key in query) {
        if (query[key] !== null) {
            url += (key + '=' + encodeURIComponent(query[key]) + '&');
        }
    }
    return url.substring(0, url.lastIndexOf('&'));
}

export function arrayGroup(data, len) {
    let result = [];
    for (let i = 0; i < data.length; i += len) {
        result.push(data.slice(i, i + len));
    }
    return result;
}

export function upload(upFileUrl, field = 'image') {
    return new Promise(function (resolve, reject) {
        uni.uploadFile({
            url: getApi('/api/upload/image'),
            name: field,
            header: {
                'Authorization': 'Bearer ' + getToken(),
                'X-Requested-With': 'XMLHttpRequest'
            },
            filePath: upFileUrl,
            success: (res) => {
                let data = JSON.parse(res.data)
                uni.hideLoading()
                resolve(data.data);
            },
            fail(res) {
                uni.showToast({
                    title: 'error',
                    icon: 'none'
                });
                uni.hideLoading()
                reject(res);
            }
        });
    })
}

export function formatNumber(amount = '0', precision = 2) {
    if (typeof amount == 'string') {
        amount = parseFloat(amount).toFixed(precision)
    } else {
        amount = amount.toFixed(precision)
    }
    return amount
}

export function restartApp() {
    // #ifdef H5
    location.reload();
    // #endif
    // #ifdef MP-WEIXIN
    uni.reLaunch({url: '/pages/home/home'});
    // #endif
    // #ifdef APP-PLUS
    // 在App平台，你可能需要自定义方法来关闭所有页面然后重新打开首页
    plus.android.importClass(plus.android.context.getPackageName()); // 示例代码，具体实现依赖于你的App平台和需求
    // 或者使用 uni.navigateBack 的组合使用直到根页面，然后 reLaunch 到首页
    uni.navigateBack({
        delta: getCurrentPages().length // 返回的页面数，默认为 1
    });
    uni.reLaunch({url: '/pages/home/home'});
    // #endif
}

export function formatSymbol(symbol) {
    if (symbol === 'BRL') {
        return 'R$'
    }
    return ''
}

export function toPage(path, isTabbar = false) {
    if (isTabbar) {
        uni.switchTab({url: path})
    } else {
        uni.navigateTo({url: path})
    }
}